package kroketwebspring.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kroketwebspring.dao.ProductDAO;
import kroketwebspring.dao.ProductDAOImpl;
import kroketwebspring.domain.Product;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class ProcessCartController extends AbstractController {
	private ProductDAO productDAO;
	
	public void setProductDAO(ProductDAOImpl productDAO) {
		this.productDAO = productDAO;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession(true);
		
		String sPId = request.getParameter("pId");
		String sAmount = request.getParameter("amo");
		String sRemProd = request.getParameter("rPd");
		
		if (sPId != null && !sPId.equals("") && sAmount != null && !sAmount.equals("")) {
			productDAO.addProductToSession(Integer.parseInt(sPId), Integer.parseInt(sAmount), session);
		} else if (sRemProd != null && !sRemProd.equals("")) {
			productDAO.removeProductFromSession(Integer.parseInt(sRemProd), session);
		}
		
		Map m = new HashMap();
		
		ArrayList<Product> shoppingCartProducts = productDAO.getProductsArrayList(session);
		
		m.put("shoppingCartProducts", shoppingCartProducts);
		return new ModelAndView("shoppingCart", m);
	}

}
